<template>
  <el-dialog v-model="dialogVisible" title="编辑房租信息" width="700px" align-center :before-close="handleCancel" class="rent-bind-dialog">
    <div class="rent-bind-container">
      <!-- 分组信息显示 -->
      <div class="group-info-section">
        <h4>所属分组：{{ tableItem.groupName }}</h4>
        <div class="group-details">
          <el-tag>分组编码：{{ tableItem.groupCode }}</el-tag>
          <el-tag type="info">用途：{{ tableItem.usage }}</el-tag>
          <el-tag type="success">计费单价：{{ tableItem.billingMethod }}</el-tag>
        </div>
      </div>

      <!-- 房租信息配置表单 -->
      <div class="rent-config-section">
        <h4>房租信息</h4>

        <!-- 批量设置区域 -->
        <el-card class="batch-config-card" shadow="never">
          <el-form ref="formRef" :model="tableItem" :rules="rules" label-width="100px" size="default">
            <el-form-item label="房租名称" prop="rentName">
              <el-input v-model="tableItem.rentName" placeholder="请输入房租名称" style="width: 300px" />
            </el-form-item>
            <el-form-item label="房租面积" prop="rentArea">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input-number v-model="tableItem.rentArea" :precision="2" :step="0.1" :min="0" style="width: 300px"
                  controls-position="right" placeholder="平方米" />
                <span>m²</span>
              </div>
            </el-form-item>
            <el-form-item label="租期" prop="leaseTerm">
              <el-select v-model="tableItem.leaseTerm" placeholder="请选择租期" style="width: 300px; text-align: center;">
                <el-option label="1个月" value="1个月" />
                <el-option label="3个月" value="3个月" />
                <el-option label="半年" value="半年" />
                <el-option label="1年" value="1年" />
                <el-option label="2年" value="2年" />
                <el-option label="3年" value="3年" />
                <el-option label="5年" value="5年" />
                <el-option label="长期" value="长期" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="tableItem.startDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 300px" />
            </el-form-item>
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="tableItem.endDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 300px" />
            </el-form-item>
            <el-form-item label="所在地点位置" prop="location">
              <div style="display: flex; align-items: center; gap: 8px;">
                <span>{{tableItem.location}}</span>                
                <el-button type="primary" @click="openLocationDialog">选择地点位置</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="isSubmitting">保存</el-button>
      </div>
    </template>

    <!-- 地点位置管理对话框 -->
    <LocationSelectDialog ref="locationSelectDialog" @confirm="handleLocationConfirm" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import LocationSelectDialog from './LocationSelectDialog.vue'
import type { MrsRent } from '@/api/types/rent'

const emit = defineEmits(['createRent', 'updateRent'])

// 响应式数据
const dialogVisible = ref(false)
const isSubmitting = ref(false)
const locationSelectDialog = ref()
const formRef = ref()

// 房租信息
const tableItem = reactive({
  id: null,
  rentName: '',
  rentArea: 0.0,
  leaseTerm: '',
  startDate: '',
  endDate: '',
  locationId: null,
  location: '',
  groupId: null,
  enterpriseId: null,
  tenantId: null,
  groupName: '',
  groupCode: '',
  usage: '',
  billingMethod: '',
})

const rules = {
  rentName: [
    { required: true, message: '请输入房租名称', trigger: 'blur' }
  ],
  rentArea: [
    { required: true, message: '房租面积不能为空', trigger: 'blur' }
  ],
  leaseTerm: [
    { required: true, message: '租期不能为空', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '开始日期不能为空', trigger: 'blur' }
  ],
  endDate: [
    { required: true, message: '结束日期不能为空', trigger: 'blur' }
  ],
}

const reset = () => {
  Object.assign(tableItem, {
    id: null,
    rentName: '',
    rentArea: 0.0,
    leaseTerm: '',
    startDate: '',
    endDate: '',
    locationId: null,
    location: '',
    groupId: null,
    enterpriseId: null,
    tenantId: null,
    groupName: '',
    groupCode: '',
    usage: '',
    billingMethod: ''
  })
  formRef.value?.clearValidate()
}

// 打开新增房租方法
const openDialog = (groupData: any) => {
  // 设置分组信息
  Object.assign(tableItem, {
    groupId: groupData.groupId,
    groupName: groupData.groupName,
    groupCode: groupData.groupCode,
    usage: groupData.usage,
    billingMethod: groupData.billingMethod,
    enterpriseId: groupData.enterpriseId,
    tenantId: groupData.tenantId,
  })
  
  isSubmitting.value = false  
  dialogVisible.value = true
}

// 打开编辑房租方法
const openEditDialog = (rentData: any) => {
  // 设置分组信息
  Object.assign(tableItem, rentData)
  
  isSubmitting.value = false  
  dialogVisible.value = true
}

const openLocationDialog = () => {
  locationSelectDialog.value?.openDialog(tableItem.tenantId)
}

const handleLocationConfirm = (selectedItem: any) => {
  console.log('位置选择确认:', selectedItem)
  
  if (!selectedItem) {
    ElMessage.warning('未选择任何位置')
    return
  }

  tableItem.locationId = selectedItem.id
  tableItem.location = selectedItem.path
}

const handleConfirm = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return
    }
    try {
      isSubmitting.value = true
      const rentInfo: MrsRent = {
        id: tableItem.id,
        rentName: tableItem.rentName,
        rentArea: Number(tableItem.rentArea),
        leaseTerm: tableItem.leaseTerm,
        startDate: tableItem.startDate,
        endDate: tableItem.endDate,
        locationId: tableItem.locationId,
        groupId: tableItem.groupId,
        enterpriseId: tableItem.enterpriseId,
      }
      // 发送事件
      if (rentInfo.id) {
        emit('updateRent', rentInfo)
      } else {
        emit('createRent', rentInfo)
      }
      dialogVisible.value = false
    } catch (error) {
      console.log('保存房租信息失败:', error)
    } finally {
      isSubmitting.value = false
    }
  })
}

const handleCancel = () => {
  dialogVisible.value = false
}

// 暴露方法
defineExpose({
  openDialog, openEditDialog, reset
})
</script>

<style scoped>
.rent-bind-container {
  max-height: 600px;
  overflow-y: auto;
}

.group-info-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.group-info-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
}

.group-details .el-tag {
  margin-right: 8px;
}

.selected-locations-section {
  margin-bottom: 20px;
}

.selected-locations-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
}

.location-list {
  min-height: 40px;
  padding: 8px;
  border: 1px dashed #d9ecff;
  border-radius: 4px;
  background-color: #ecf5ff;
}

.location-selection-section {
  margin-bottom: 20px;
}

.rent-config-section h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.batch-config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rent-list-section {
  margin-bottom: 16px;
}

.reselect-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.hint-text {
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}
</style>